package at.jsug.topicvoting.gwt1.client.logic;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class FrontDispatcher {

	private static final FrontDispatcher INSTANCE = new FrontDispatcher();
	
	private Map<String, Set<IEventListener<? extends IEvent>>> map = new HashMap<String, Set<IEventListener<? extends IEvent>>>(); 
	
	private FrontDispatcher() {
		
	}
	
	public static FrontDispatcher getInstance() {
		return INSTANCE;
	}
	
	public void register(final String eventId, final IEventListener<? extends IEvent> listener) {
		System.out.println("FrontDispatcher.register(eventId="+eventId+";listener="+listener+")");
		
		if(this.map.containsKey(eventId) == false) {
			this.map.put(eventId, new HashSet<IEventListener<? extends IEvent>>());
		}
		
		this.map.get(eventId).add(listener);
	}
	
	public void dispatch(final IEvent event) {
		System.out.println("FrontDispatcher.dispatch(event="+event+")");
		
		if(this.map.containsKey(event.getId()) == false) {
			System.out.println("FrontDispatcher.dispatch: aborting, not anyone registered to that event.");
			return;
		}
		
		for (IEventListener<? extends IEvent> listener : this.map.get(event.getId())) {
			((IEventListener<IEvent>)listener).eventReceived(event);
		}
	}
	
	
}
